﻿using System;
using System.Collections.Generic;
using Microsoft.SharePoint;
using SimpleFS.Core;

namespace SimpleFS.Providers.SharePoint
{
    public class File : IFile
    {
        protected string fileName;

        protected SPFile file;

        protected SPWeb web;

        protected System.IO.Stream stream;

        public File(string fileName)
        {
            this.fileName = fileName;

            int index = fileName.IndexOf('/', "http://".Length + 1);
            string siteUrl = fileName.Substring(0, index);

            int idx = fileName.IndexOf('/', index + 1);
            string webUrl = fileName.Substring(index + 1, idx - index - 1);

            SPSite site = new SPSite(siteUrl);
            web = site.OpenWeb();
            file = web.GetFile(fileName);
        }

        #region IFile Members

        public System.IO.Stream Read()
        {
            this.stream = this.file.OpenBinaryStream();

            return stream;
        }

        public void Write(System.IO.Stream stream)
        {
            this.file = this.web.Files.Add(this.fileName, stream);
        }

        #endregion

        #region IFileSystemObject Members

        public string Name
        {
            get { return this.file.Name; }
        }

        public DateTime LastModifiedTime
        {
            get { return this.file.TimeLastModified; }
        }

        public Dictionary<string, string> Attributes
        {
            get { throw new NotImplementedException(); }
        }

        public IDirectory ParentDirectory
        {
            get { throw new NotImplementedException(); }
        }

        public void Copy(IFileSystemObject target)
        {
            File targetFile = target as File;
            this.file.CopyTo(target.Name);
        }

        public void Move(IFileSystemObject target)
        {
            File targetFile = target as File;
            this.file.MoveTo(targetFile.Name);
        }

        public void Delete()
        {
            this.file.Delete();
        }

        public bool Exists()
        {
            return this.file.Exists;
        }

        public void Rename(string newName)
        {
            this.file.MoveTo(newName);
        }

        public void Close()
        {
            this.stream.Close();
        }

        #endregion
    }
}
